﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Linq;
using PMSGSC.DAL;
using PMSGSC.BLL;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Localization;
using PMSGSC.Common;

namespace PMSGSC.App
{
    public partial class frmCloseJobDetail : DevExpress.XtraEditors.XtraForm
    {
        public frmCloseJobDetail(WorkOrder workOrder)
        {
            InitializeComponent();
            workOrderBindingSource.Add(workOrder);
            this.workOrder = workOrder;
            if (workOrder.Type == 3)
            {
                roundJobBindingSource.DataSource = RoundJob_BLL.GetDataByRoundID(workOrder.Round_ID.Value, false);
            }
            else
            {
                xtraTabControl1.TabPages[5].PageVisible = false;
            }
            employeeBindingSource.DataSource = Employee_BLL.GetAll(frmMain.ship.Ship_ID);
            stockBindingSource.DataSource = Stock_BLL.GetAll(frmMain.ship.Ship_ID);
        }
        WorkOrder workOrder;

        private DateTime NextDue(string Frequency, DateTime LastDone, string TimeUnit)
        {

            int Number = int.Parse(Frequency);
            DateTime dt = LastDone;
            switch (TimeUnit)
            {
                case "Day(s)":
                    dt = dt.AddDays(Number);
                    break;
                case "Week(s)":
                    int NumberDay = Number * 7;
                    dt = dt.AddDays(NumberDay);
                    break;
                case "Month(s)":
                    dt = dt.AddMonths(Number);
                    break;
            }
            return dt;
        }
        Invoice invoice = new Invoice();
        private void btnComplete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            frmProcessBar pb = new frmProcessBar();
            System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            {
                LoadSkinToForm();
                pb.ShowDialog();
            }
            ));
            thread.Start();

            workOrder.HistoryDetail = ucRichEditControl1.richEditControl1.Text;
            workOrder.OverdueReason = ucRichEditControl2.richEditControl1.Text;
            workOrder.Complete = true;
            workOrder.StatusJob = BaseDAL.DB.StatusJobs.Single(n => n.StatusJob_ID == 3);
            workOrder.ReportBy = "Teo";

            WorkOrder_BLL.Update(workOrder);

            if (workOrder.Type == 1 || workOrder.Type == 2)
            {
                History history = new History();
                history.Job_ID = workOrder.Job_ID;
                history.WorkOrder_ID = workOrder.WorkOrder_ID;

                History_BLL.Insert(history);
            }

            if (resourceUseBindingSource.Count > 0)
            {
                foreach (ResourceUse resource in resourceUseBindingSource.Cast<ResourceUse>().ToList())
                {
                    ResourceUse_BLL.Insert(resource);
                }
            }

            if (invoiceDetailBindingSource.Count > 0)
            {
                invoice.Employee_ID = frmMain.UserLogin.Employee_ID;
                invoice.Equipment_ID = workOrder.Equipment_ID;

                invoice.InvoiceCode = "OUT" + DateTime.Now.Year + Invoice_BLL.GetOrderNumberVoucherOut();
                invoice.InvoiceDate = DateTime.Now.Date;
                invoice.TransType = "Used";
                invoice.Ship_ID = frmMain.ship.Ship_ID;
                invoice.Type = false;
                invoice.WorkOrder_ID = workOrder.WorkOrder_ID;
                Invoice_BLL.Insert(invoice);
                invoice = Invoice_BLL.GetNewInvoice();
                InsertValueIntoInvoiceDetail();
            }

            if (workOrder.Type == 1)
            {
                Job newJob = Job_BLL.GetDataById(workOrder.Job_ID.Value);
                if (newJob.TimeUnit != "Hour(s)")
                {
                    newJob.LastDone = DateTime.Now.Date;
                    newJob.NextDue = NextDue(newJob.FreodicFrequency.ToString(), newJob.LastDone.Value, newJob.TimeUnit);
                    newJob.TimeDone = null;
                }
                else
                {
                    newJob.TimeDone = 0;
                    newJob.LastDone = null;
                    newJob.NextDue = null;
                }

                Job_BLL.Update(newJob);

                WorkOrder newWorkOrder = new WorkOrder();
                newWorkOrder.CreateDate = DateTime.Now.Date;
                newWorkOrder.Detail = newJob.Details;
                newWorkOrder.EmployeeCreate = frmMain.UserLogin.Name;
                newWorkOrder.Equipment_ID = newJob.Equipment_ID.Value;
                newWorkOrder.Frequency = newJob.FreodicFrequency;
                newWorkOrder.IsCheck = false;
                newWorkOrder.LastDone = newJob.LastDone;
                newWorkOrder.Job_ID = newJob.Job_ID;
                newWorkOrder.RespDescipline_ID = newJob.Employee_ID;
                newWorkOrder.SC_ID = newJob.SC_ID;
                newWorkOrder.Ship_ID = newJob.Equipment.Ship_ID;
                newWorkOrder.StatusJob_ID = 1;
                newWorkOrder.TimeUnit = newJob.TimeUnit;
                newWorkOrder.Title = newJob.JobDescription.CodeJD + "-" + newJob.JobDescription.NameJD;
                newWorkOrder.Type = 1;
                newWorkOrder.Complete = false;
                newWorkOrder.WorkOrderNumber = frmMain.ship.CodeShip + "/" + GetLastTwoNumber(DateTime.Now.Date.Year) + "/" + WorkOrder_BLL.GetQuantityWorkOrder(frmMain.ship.Ship_ID).ToString("00000");

                if (newJob.TimeUnit == "Hour(s)")
                {
                    newWorkOrder.NextDue = null;
                    newWorkOrder.AlarmDaybefore = null;
                    newWorkOrder.TimeDone = newJob.TimeDone;
                }
                else
                {
                    newWorkOrder.TimeDone = null;
                    newWorkOrder.NextDue = newJob.NextDue;
                    newWorkOrder.AlarmDaybefore = newJob.AlarmDaybefore;
                }
                WorkOrder_BLL.Insert(newWorkOrder);
            }
            else
            {
                if (workOrder.Type == 3)
                {
                    workOrder.Round.LastDone = DateTime.Now.Date;
                    workOrder.Round.NextDue = NextDue(workOrder.Round.Frequency.ToString(), workOrder.Round.LastDone.Value, workOrder.Round.TimeUnit);
                    Round_BLL.Update(workOrder.Round);

                    if (roundJobBindingSource.Count > 0)
                    {
                        foreach (RoundJob rj in roundJobBindingSource.Cast<RoundJob>().ToList())
                        {
                            Job j = Job_BLL.GetDataById(rj.Job_ID);
                            j.LastDone = DateTime.Now.Date;
                            j.NextDue = NextDue(j.FreodicFrequency.ToString(), j.LastDone.Value, j.TimeUnit);
                            Job_BLL.Update(j);

                            History historyType3 = new History();
                            historyType3.Job_ID = rj.Job_ID;
                            historyType3.WorkOrder_ID = workOrder.WorkOrder_ID;

                            History_BLL.Insert(historyType3);
                        }
                    }

                    WorkOrder newworkOrder = new WorkOrder();
                    newworkOrder.CreateDate = DateTime.Now.Date;
                    int CountJob = WorkOrder_BLL.GetQuantityWorkOrder(frmMain.ship.Ship_ID);

                    newworkOrder.WorkOrderNumber = "NN" + "/" + GetLastTwoNumber(DateTime.Now.Date.Year) + "/" + CountJob.ToString();
                    newworkOrder.Title = workOrder.Round.RoundCode + "-" + workOrder.Round.Title;
                    newworkOrder.Frequency = workOrder.Round.Frequency;
                    newworkOrder.TimeUnit = workOrder.Round.TimeUnit;
                    newworkOrder.LastDone = workOrder.Round.LastDone;
                    newworkOrder.NextDue = workOrder.Round.NextDue;
                    newworkOrder.AlarmDaybefore = workOrder.Round.AlarmDayBefore;
                    newworkOrder.JobDescription = workOrder.Round.Detail;
                    newworkOrder.RespDescipline_ID = workOrder.Round.Employee_ID;
                    newworkOrder.StatusJob_ID = 1;
                    newworkOrder.SC_ID = workOrder.Round.ServiceCode_ID;
                    newworkOrder.Ship_ID = workOrder.Round.Ship_ID;
                    newworkOrder.IsCheck = false;
                    newworkOrder.Complete = false;
                    newworkOrder.Type = 3;
                    newworkOrder.Round_ID = workOrder.Round.Round_ID;
                    newworkOrder.EmployeeCreate = frmMain.UserLogin.Name;

                    bool kq = WorkOrder_BLL.Insert(newworkOrder);
                }
            }


            if (pb.InvokeRequired)
                pb.BeginInvoke(new Action(() => pb.Close()));

            XtraMessageBox.Show("Save Successfully!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Close();
        }

        private static void LoadSkinToForm()
        {
            DevExpress.Skins.SkinManager.EnableFormSkins();
            DevExpress.UserSkins.BonusSkins.Register();
            DevExpress.UserSkins.OfficeSkins.Register();
            DevExpress.LookAndFeel.DefaultLookAndFeel obj = new DevExpress.LookAndFeel.DefaultLookAndFeel();
            try
            {
                LookAndFeelSettings.Load("LookAndFeelSettings.dat");
            }
            catch
            {
                obj.LookAndFeel.SetSkinStyle("Blue");
            }
        }

        private int GetLastTwoNumber(int year)
        {
            return year % 1000;
        }
        private void InsertValueIntoInvoiceDetail()
        {
            foreach (InvoiceDetail invoiceDetail in invoiceDetailBindingSource.Cast<InvoiceDetail>().ToList())
            {
                invoiceDetail.Invoice = BaseDAL.DB.Invoices.Single(n => n.Invoice_ID == invoice.Invoice_ID);
                InvoiceDetail_BLL.Update(invoiceDetail);

                LocationInStock newLocation = LocationInStock_BLL.isExits2(invoiceDetail.Part_ID.Value, invoiceDetail.Stock_ID.Value);
                if (null != newLocation)
                {
                    newLocation.Quantity -= invoiceDetail.Quantity.Value;
                    LocationInStock_BLL.Update(newLocation);
                }
            }
        }
        private void gleEmployeeName_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            try
            {
                ((ResourceUse)gridView1.GetFocusedRow()).Employee = BaseDAL.DB.Employees.Single(n => n.Employee_ID == (int)e.NewValue);
            }
            catch { }
        }

        private void gluEmployee_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            try
            {
                ((ResourceUse)gridView1.GetFocusedRow()).Employee = BaseDAL.DB.Employees.Single(n => n.Employee_ID == (int)e.NewValue);
            }
            catch { }
         
        }

        private void gridView1_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            GridView view = sender as GridView;

            GridColumn TimeCol = view.Columns["Time"];
            view.SetRowCellValue(e.RowHandle, TimeCol, 0);
        }

        private void gridView1_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void gridView2_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void gridView2_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {

            GridView view = (GridView)sender;
            GridColumn PartCol = view.Columns[2];
            GridColumn PartNameCol = view.Columns[3];
            GridColumn QuantityCol = view.Columns[5];


            GridColumn StockCol = view.Columns["Stock_ID"];

            if (null == invoiceDetail.PartsInEquipment)
            {
                e.Valid = false;
                view.FocusedColumn = PartCol;
                e.ErrorText = "Please enter the Part. ";
                view.SetColumnError(PartCol, "Part is not empty");
                view.SetColumnError(PartNameCol, "Part is not empty");
                return;
            }
            if (!LocationInStock_BLL.ExitsInStock(invoiceDetail.Part_ID.Value))
            {
                e.Valid = false;
                view.FocusedColumn = PartCol;
                e.ErrorText = "Please enter the Part. ";
                view.SetColumnError(PartCol, "Part is not exit in Stock");
                view.SetColumnError(PartNameCol, "Part is not exit in Stock");
                return;
            }
            if (null == view.GetRowCellValue(e.RowHandle, StockCol))
            {
                e.Valid = false;
                view.FocusedColumn = StockCol;
                e.ErrorText = "Please enter the Stock. ";
                view.SetColumnError(StockCol, "Stock is not empty");
                 return;
            }
            if (null != view.GetRowCellValue(e.RowHandle, QuantityCol) && invoiceDetail.Stock != null)
            {
                if (LocationInStock_BLL.TestQuantityPart(invoiceDetail.Part_ID.Value, invoiceDetail.Stock_ID.Value) - TestTotal() < invoiceDetail.Quantity.Value)
                {
                    e.Valid = false;
                    view.FocusedColumn = QuantityCol;
                    e.ErrorText = "Please enter the Quantity. ";
                    view.SetColumnError(QuantityCol, "Quantity phai nho hon");
                }
            }
        }
        private int TestTotal()
        {
            int Quantity = 0;
            for (int i = 0; i < invoiceDetailBindingSource.Cast<InvoiceDetail>().ToList().Count - 1; i++)
            {
                if (invoiceDetailBindingSource.Cast<InvoiceDetail>().ToList()[i].Part_ID == invoiceDetail.Part_ID)
                    Quantity += invoiceDetailBindingSource.Cast<InvoiceDetail>().ToList()[i].Quantity.Value;
            }
            return Quantity;
        }

        private void gridView2_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            if (e.RowHandle == GridControl.NewItemRowHandle)
            {
                e.WindowCaption = "Input Error";
            }
            else
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
                DialogResult dr = XtraMessageBox.Show(gridControl1.LookAndFeel, this, e.ErrorText + GridLocalizer.Active.GetLocalizedString(GridStringId.ColumnViewExceptionMessage), e.WindowCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                if (dr == DialogResult.No)
                {
                    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                    gridView2.DeleteRow(gridView2.FocusedRowHandle);
                }
            }
        }

        private static void OnlyInputNumberic(KeyPressEventArgs e)
        {
            const char Delete = (char)8;
            e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
        }

        private void gridView2_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            GridView view = (GridView)sender;
            GridColumn QuantityCol = view.Columns["Quantity"];
            view.SetFocusedRowCellValue(QuantityCol, 0);
        }

        private void btnPart_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

            frmGridPart gridPart = new frmGridPart();
            gridPart.ShowDialog();
            if (gridPart.PartsInEquipment != null)
            {
                GridView view = gridControl1.FocusedView as GridView;
                if (view.IsNewItemRow(view.FocusedRowHandle) && view.GetRow(view.FocusedRowHandle) == null)
                {
                    view.AddNewRow();
                }
                invoiceDetail.PartsInEquipment = BaseDAL.DB.PartsInEquipments.Single(n => n.Parts_ID == (int)gridPart.PartsInEquipment.Parts_ID);
            }

        }
        InvoiceDetail invoiceDetail;
        private void invoiceDetailBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            invoiceDetail = invoiceDetailBindingSource.Current as InvoiceDetail;
        }

        private void stock_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            try
            {
                ((InvoiceDetail)gridView2.GetFocusedRow()).Stock= BaseDAL.DB.Stocks.Single(n => n.Stock_ID == (int)e.NewValue);
            }
            catch(Exception ex)
            { }
        }

        private void gridView3_ShowingEditor(object sender, CancelEventArgs e)
        {
            GridView view = sender as GridView;
            GridColumn IsCheckCol = view.Columns["IsCheck"];
            if (!view.IsNewItemRow(view.FocusedRowHandle) && view.FocusedColumn != IsCheckCol)
                e.Cancel = true;
        }

        private void gridView2_ShowingEditor(object sender, CancelEventArgs e)
        {
            GridView view = sender as GridView;
            GridColumn IsCheckCol = view.Columns["IsCheck"];
            if (!view.IsNewItemRow(view.FocusedRowHandle) && view.FocusedColumn != IsCheckCol)
                e.Cancel = true;
        }

        private void gluEmployee_EditValueChanged(object sender, EventArgs e)
        {
            gridView1.PostEditor();
        }

        private void gleEmployeeName_EditValueChanged(object sender, EventArgs e)
        {
            gridView1.PostEditor();
        }

        private void Hours_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }

        private void Quantity_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }

        private void gridView3_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            ResourceUse ru = resourceUseBindingSource.Current as ResourceUse;
            ru.WorkOrder_ID = workOrder.WorkOrder_ID;
        }
    }
}